package com.example.spider.common.util;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

public class MyThreadFactory implements ThreadFactory {

    private final ThreadGroup threadGroup;
    private final AtomicLong threadSeq = new AtomicLong(1);
    private final String threadNamePrefix;
    private boolean daemon = true;

    public MyThreadFactory(String groupName, boolean isDaemon) {
        this.daemon = isDaemon;
        this.threadNamePrefix = groupName;
        this.threadGroup = new ThreadGroup(groupName);
    }


    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(threadGroup, r, threadNamePrefix + threadSeq.getAndIncrement(), 0);
        t.setDaemon(daemon);
        //recovery thread priority
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }

}